﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Threading;
using System.Timers;
using Common;
using System.ServiceModel;

namespace ClientManager
{
    public class WCFLabWorker : BackgroundWorker
    {
        protected void WorkerTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (CancellationPending)
            {
                WorkerTimer.Stop();
            }
            else
            {
                WCFClient.Work();

                Repetition++;

                Action<WCFWorkerArgs> PassStatus = (args) => NotifyRepetition(this, args);
                Dispatcher.BeginInvoke(PassStatus, DispatcherPriority.Normal, new WCFWorkerArgs
                    {
                        ClientId = this.ClientId,
                        Repetition = this.Repetition,
                        SessionId = WCFClient.InnerChannel.SessionId,
                        StatusTimestamp = DateTime.Now
                    });
            }
        }

        public virtual void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (WorkerTimer == null)
            {
                WCFClient = new BasicClient(ClientId, Repetition);

                WorkerTimer = new Timer(Delay);
                WorkerTimer.Elapsed += new ElapsedEventHandler(WorkerTimer_Elapsed);
            }

            WorkerTimer.Start();
        }

        public event EventHandler NotifyRepetition;

        protected override void Dispose(bool disposing)
        {
            ((ICommunicationObject)WCFClient).Close();

            base.Dispose(disposing);
        }

        public WCFLabWorker()
            : base()
        {
            WorkerSupportsCancellation = true;

            Repetition = 0;
        }

        public BasicClient WCFClient { get; private set; }

        public string ClientId { get; set; }

        public int Delay { get; set; }

        public int Repetition { get; private set; }

        public Timer WorkerTimer { get; private set; }

        public Dispatcher Dispatcher { get; set; }
    }
}
